import pymysql


class DButils:
    def __init__(self, host, user, password, database):
        self.host = host
        self.user = user
        self.password = password
        self.database = database

    def Select(self, sql, data=None):
        connect = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database)
        cursor = connect.cursor()
        try:
            cursor.execute(sql, data)
            result = cursor.fetchall()
            return result
        except Exception:
            print('查询失败', Exception)
        finally:
            cursor.close()
            connect.close()

    def Update(self, sql, data=None):
        connect = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database)
        cursor = connect.cursor()
        try:
            cursor.execute(sql, data)
            connect.commit()
            return True
        except Exception as e:
            print('修改数据库失败', e)
        finally:
            cursor.close()
            connect.close()


if __name__ == '__main__':
    db = DButils('127.0.0.1', 'root', '20191024', 'mysqlstudy')
    sql = '''create table person
(
    username varchar(20),
    age      int,
    sex      char(4),
    high     double(3, 2) # 总共3位数字，2位小数
)'''
    db.Update(sql)
    for i in range(10):
        username = input('请输入用户名：')
        age = int(input('请输入年龄：'))
        sex = input('请输入性别：')
        high = float(input('请输入身高(3位数字，两位小数)：'))
        sql = '''insert into person(username,age,sex,high) values(%s,%s,%s,%s)'''
        data = (username, age, sex, high)
        db.Update(sql, data)
        print('添加成功')
